package com.cym.test.filter;


import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class SetEcoding implements Filter {
    protected String encoding = null;
    private boolean enabled;//是否启用该filter,配置在web.xml中
    public SetEcoding() {

    }
    public void init(FilterConfig fConfig) throws ServletException {
        encoding = fConfig.getInitParameter("encoding");
        enabled = "true".equalsIgnoreCase(fConfig.getInitParameter("enabled").trim());
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (enabled || encoding != null) {
            request.setCharacterEncoding(encoding);
            response.setCharacterEncoding(encoding);
            response.setContentType("text/html; charset="+encoding);
        }
        chain.doFilter(request, response);
    }

    public void destroy() {
        this.encoding = null;
    }

}

